package cn.edu.zut.salarymanagesystem.fragments;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.edu.zut.salarymanagesystem.R;
import cn.edu.zut.salarymanagesystem.activities.AddSpecialActivity;
import cn.edu.zut.salarymanagesystem.bean.pojo.Append;
import cn.edu.zut.salarymanagesystem.bean.pojo.Item;
import cn.edu.zut.salarymanagesystem.bean.pojo.Work;
import cn.edu.zut.salarymanagesystem.bean.vo.ListItemResult;
import cn.edu.zut.salarymanagesystem.config.Storage;
import cn.edu.zut.salarymanagesystem.utils.AlertBuilder;
import cn.edu.zut.salarymanagesystem.utils.Browser;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddFragment extends Fragment {
    private static final int ADD_EXCEPTION = -1;
    private static final int ADD_ERROR = 0;
    private static final int ADD_SUCCESS = 1;
    private static final int BAD_REQ_FORMAT = 2;
    private static final int REND_ITEM_LIST = 3;

    Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REND_ITEM_LIST:
                    String json = (String) msg.obj;
                    ListItemResult result = JSON.parseObject(json, ListItemResult.class);
                    itemList = result.getList();
                    itemNames.clear();
                    itemList.forEach(item -> itemNames.add(item.getObjectName()));
                    adapter.notifyDataSetChanged();
                    break;
                case ADD_SUCCESS:
                    editComment.setText("");
                    AlertBuilder.getAddDialog(getActivity(), (String) msg.obj).show();
                    break;
            }
        }
    };
    ArrayAdapter<String> adapter;
    private List<Item> itemList;
    private Button btnAddCommon;
    private EditText editComment;
    private EditText editPriceChange;
    private Button btnAddSpecial;
    private Spinner spnItemList;
    private Spinner spnNum;
    private List<String> itemNames = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add, container, false);
        //初始化界面
        initView(view);
        //绑定事件
        spnNum.setAdapter(new ArrayAdapter<>(getActivity(), R.layout.simple_spinner_item, android.R.id.text1, new String[]{"1", "2", "3", "4", "5"}));
        adapter = new ArrayAdapter<>(getActivity(), R.layout.simple_spinner_item, android.R.id.text1, itemNames);
        spnItemList.setAdapter(adapter);
        btnAddCommon.setOnClickListener(this.addCommonListener);
        btnAddSpecial.setOnClickListener(this.addSpecialListener);
        //请求列表集合i
        OkHttpClient client = Browser.getClient();
        Request request = new Request.Builder().url(Storage.url + "/item/listMy").build();
        //此处动态展示条目列表逻辑;
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String json = response.body().string();
                Message msg = Message.obtain();
                msg.what = REND_ITEM_LIST;
                msg.obj = json;
                handler.sendMessage(msg);
            }
        });
        return view;
    }
    private void initView(View view) {
        ((TextView) view.findViewById(R.id.group_name)).setText("您在 " + Storage.currentUser.getGroupName());
        ((TextView) view.findViewById(R.id.username)).setText("欢迎您 " + Storage.currentUser.getUserName());
        btnAddCommon = view.findViewById(R.id.btn_add_common);
        btnAddSpecial = view.findViewById(R.id.btn_add_special);
        spnItemList = view.findViewById(R.id.type_select);
        editComment = view.findViewById(R.id.edit_comment);
        editPriceChange = view.findViewById(R.id.edit_price_change);
        spnNum = view.findViewById(R.id.spn_number_select);
    }
    private View.OnClickListener addCommonListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //先校验数据，然后生成对象，提交请求
            Work work = new Work();
            int itemPos = spnItemList.getSelectedItemPosition();
            work.setValue(itemList.get(itemPos).getValue());
            work.setUid(Storage.currentUser.getUid());
            work.setTime(new Date());
            work.setNumber(spnNum.getSelectedItemPosition() + 1);
            work.setOid(itemList.get(itemPos).getOid());
            work.setPlus(Integer.parseInt(editPriceChange.getText().toString()));
            work.setCommentary(editComment.getText().toString());
            String jsonString = JSON.toJSONString(work);
            Log.i("d8g", jsonString);
            OkHttpClient client = Browser.getClient();
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString);
            Request request = new Request.Builder().
                    url(Storage.url + "/workRecord/insertWork").
                    post(body).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e("d8g", "!" + e.getMessage());
                    e.printStackTrace();
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    String res = response.body().string();
                    Message obtain = new Message();
                    obtain.what = ADD_SUCCESS;
                    obtain.obj = res.equals("1") ? "添加成功！" : "添加失败！";
                    handler.sendMessage(obtain);
                }
            });
        }
    };
    //TODO:请翟艺婷修复这里添加按钮没有响应的问题
    private final View.OnClickListener addSpecialListener = view -> {
        Intent intent = new Intent(getActivity(), AddSpecialActivity.class);
        startActivityForResult(intent, ADD_SUCCESS);
    };
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //这个是接收数据的回调函数
        if (requestCode == ADD_SUCCESS && resultCode == 100) {
            Append item = new Append();
            item.setCommentary(data.getStringExtra("commentary"));
            item.setValue(Integer.valueOf(data.getStringExtra("price")));
            item.setTime(new Date());
            item.setUid(Storage.currentUser.getUid());
            item.setPlus(1);//增加一条记录
            String jsonString = JSON.toJSONString(item);
            OkHttpClient client = Browser.getClient();
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString);
            //在这里拼接上对应接口的url地址
            Request request = new Request.Builder().
                    url(Storage.url + "/workRecord/insertAppend").
                    post(body).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    String res = response.body().string();
                    System.out.println("-1---" + res);
                    Message obtain = new Message();
                    obtain.what = ADD_SUCCESS;
                    obtain.obj = res.equals("1") ? "添加成功！" : "添加失败！";
                    handler.sendMessage(obtain);
                }
            });
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}